package me.helllp.book.concurrent.ch05;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 并行查找的演示
 * 
 * @author Administrator
 *
 */
public class SearchTask implements Callable<Integer>{
	int begin, end, searchValue;
	
	static int[] arr = new int[100000000];
	
	static ExecutorService pool = Executors.newCachedThreadPool();
	static final int Thread_Num = 3;
	static AtomicInteger result = new AtomicInteger(-1);
	
	public SearchTask(int searchValue,int beging,int end) {
		this.begin = beging;
		this.end = end;
		this.searchValue = searchValue;
	}
	
	@Override
	public Integer call() throws Exception {
		int re = search(this.searchValue, begin, end);
		return re;
	}
	
	public int search(int searchValue, int beginPos, int endPos){
		int i=0;
		
		for(i=beginPos; i<endPos; i++){
			if(result.get() >= 0){
				return result.get();
			}
			
			if(arr[i] == searchValue){
				if(!result.compareAndSet(-1, i)){
					return result.get();
				}
				return i;
			}
		}
		
		return -1;
	}
	
	public int pSearch(int searchValue) throws InterruptedException, ExecutionException{
		int subArrSize = arr.length / Thread_Num + 1;
		List<Future<Integer>> re = new ArrayList<Future<Integer>>();
		
		for(int i=0; i<arr.length; i+=subArrSize){
			int end = i + subArrSize;
			if(end >= arr.length) {
				end = arr.length;
			}
			re.add(pool.submit(new SearchTask(searchValue, i, end)));
		}
		
		for(Future<Integer> fu : re){
			if(fu.get() >= 0){
				return fu.get();
			}
		}
		
		return -1;
	}
	
	private static int initArr(int searchKey){
		boolean isSet = false;
		
		Random rand = new Random();
		int iTemp = 0;
		
		for(int i=0; i<arr.length; i++){
			while(true){
				arr[i] = rand.nextInt();
				
				if(!isSet){
					if(arr[i] == searchKey){
						iTemp = i;
						isSet = true;
					}
					break;
				}else{
					if(arr[i] == searchKey){
						continue;
					}else{
						break;
					}
				}
			}
		}
		
		if(!isSet){
			iTemp = rand.nextInt(arr.length-1); 
			arr[iTemp] = searchKey;
		}
		
		return iTemp;
	}
	
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		//	准备数据
		int searchKey = 3789407;
		int iIndex = initArr(searchKey);

		System.out.println("准备数据的结果：" + iIndex);
		
		SearchTask task = new SearchTask(searchKey, 0, arr.length);

		long s = System.currentTimeMillis();
		int searchResult =  task.pSearch(searchKey);
		long e = System.currentTimeMillis();
		
		System.out.println("查找数据的结果：" + searchResult);
		System.out.println("执行时间：" + (e-s));
	}
}
